package mx.realm;

import javax.annotation.Resource;

import mx.entity.Manage;
import mx.service.ManageService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * 自定义realm
 * 
 * @author
 * 
 */
public class MyRealm extends AuthorizingRealm {

	@Resource
	private ManageService manageService;

	/**
	 * 为当前的登录得用户角色和权限
	 * 
	 * @param principals
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	/**
	 * 验证当前登陆的用户
	 * 
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		Manage manage = manageService.getByUserName(userName);
		if (null != manage) {
			Session session = SecurityUtils.getSubject().getSession();
			session.setAttribute("currentUser", manage);
			AuthenticationInfo authInfo = new SimpleAuthenticationInfo(manage.getUserName(), manage.getPassword(),
					"xxxxx");
			return authInfo;
		} else {
			return null;
		}
	}

}
